package com.example.multidatasource.config;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    public static void setDataBaseName(String dbName){
        contextHolder.set(dbName);
    }

    public static String getDataBaseName(){
        return contextHolder.get();
    }

    public static void clearDataBaseName(){
        contextHolder.remove();
    }

    /**
     * 实现此方法决定使用哪个数据源
     * @return
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return getDataBaseName();
    }
}
